package org.example.task;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;

/**
 * @Author wangf
 * @Description TODO JavaAPI - 文档高级查询封装
 * @Date 2023/3/6 17:01
 */
public class QueryDoc {
    @FunctionalInterface
    public interface QueryBuild {
        void doBuild(SearchRequest request, SearchSourceBuilder sourceBuilder) throws IOException;
    }

    public static void doQuery(RestHighLevelClient client, QueryBuild build) throws IOException {
        //创建查询请求对象
        SearchRequest request = new SearchRequest();
        request.indices("user");
        //创建查询条的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //请求体由调用者进行
        build.doBuild(request, sourceBuilder);
        request.source(sourceBuilder);
        //客户端发送请求，获取响应对象
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //打印结果信息
        SearchHits hits = response.getHits();
        System.out.println("timeout:" + response.isTimedOut());
        System.out.println("total:" + hits.getTotalHits());
        System.out.println("MaxScore:" + hits.getMaxScore());
        System.out.println("hits========>>");
        hits.forEach(hit -> {
            System.out.println(hit.getSourceAsString());
        });
        System.out.println("<<========");
    }

}
